import React, { Component } from 'react'
import axios from 'axios';
import PubSub from 'pubsub-js';
import { NavLink } from 'react-router-dom'
export default class List extends Component {
    state = {
        heros: [],
    }
    render () {
        return (
            <div>
                {
                    this.state.heros.map(item => {
                        return <div className="item" key={item.id}>
                            <NavLink to={"/hero-detail?id=" + item.id}>
                                <img src={'http://127.0.0.1:3002' + item.image} width="100%" alt="" />
                            </NavLink>
                            <h5>{item.name}</h5>
                        </div>
                    })
                }
            </div>
        )
    }


    //组件挂载完毕之后的回调
    async componentDidMount () {
        //订阅频道 获取关键字
        PubSub.subscribe('hero-name', async (c, data) => {
            //发送AJAX
            let result = await axios.get('http://127.0.0.1:3002/hero', { params: { q: data } });
            //设置
            this.setState({
                heros: result.data
            })
        });

        //发送 ajax 请求
        let result = await axios.get('http://127.0.0.1:3002/heros');
        this.setState({
            heros: result.data
        });


    }
}
